<?php
namespace app\common\service;

use app\common\service\WeixinService;
use think\Db;
use think\Model;
use think\Request;

class MsgService extends BaseService
{
    //消息模板列表
    public function GetStoreSetting($sid)
    {
        $where = ['m.sid' => $sid];
        $list_count = db('msg_setting')
            ->alias('m')
            ->join('wx_template w', 'm.sid=w.sid and m.wx_template_type=w.template_type', 'left')
            ->where($where)
            ->count();

        $msg_list = db('msg_setting')
            ->alias('m')
            ->join('wx_template w', 'm.sid=w.sid and m.wx_template_type=w.template_type', 'left')
            ->where($where)
            ->field('m.*,w.template_id')
            ->order('m.bussiness_no asc')
            ->select();
        $msg_bussiness_no = \think\Config::get('msg_bussiness_no');
        /*if (empty($msg_list)) {
            if (!empty($msg_bussiness_no) && is_array($msg_bussiness_no)) {
                $data = array();
                $data['sid'] = $sid;
                foreach ($msg_bussiness_no as $k => $v) {
                    $data['bussiness_no'] = $k;
                    $data['wx_template_type'] = 300 + intval($k);
                    $data['wx_status'] = 1;
                    $data['if_setting_receive'] = 0;
                    $data['receive_uids'] = '';
                    db('msg_setting')->insert($data);
                }
            }
            $msg_list = db('msg_setting')->alias('m')
                ->join('wx_template w', 'm.sid=w.sid and m.wx_template_type=w.template_type', 'left')
                ->where($where)
                ->field('m.*,w.template_id')
                ->order('m.bussiness_no asc')
                ->select();
        }*/
        if($msg_list){
            foreach ($msg_list as $k => $v) {
                $msg_list[$k]['bussiness_name'] = $msg_bussiness_no[$v['bussiness_no']];
                if (!empty($v['receive_uids'])) {
                    $uids = unserialize($v['receive_uids']);
                    $msg_list[$k]['receive_list'] = db('user')->whereIn('user_id', $uids)->field('user_nickname,user_headimgurl,user_id')->select();

                }
            }
        }
        return ['content' => $msg_list, 'page' => ['count' => $list_count]];
    }

    //一键删除
    public function AutoDel(Request $request)
    {
        $sid = $request->param('sid');
        $tpl = db('wx_template')->where(['sid' => $sid])->find();
        $tpl1 = db('msg_setting')->where(['sid' => $sid])->find();
        if (empty($tpl) && empty($tpl1)) {
            return ['status' => 1];
        } else {
            $res = db('wx_template')->where(['sid' => $sid])->delete();
            $res1 = db('msg_setting')->where(['sid' => $sid])->delete();
            if ($res !== false && $res1 !== false) {
                return ['status' => 1];
            } else {
                return ['status' => 0];
            }
        }
    }

    /**
     * 一键删除模版消息
     * @param $sid
     * @return array
     */
    public function deleteAllMsg($sid)
    {
        $template_no_list = db('wx_template')->where('sid', $sid)->column('template_no');
        $msg_setting = db('msg_setting')->where('sid', $sid)->find();
        if (empty($template_no_list) && empty($msg_setting)) {
            return ['status' => 1, 'msg' => '删除成功!'];
        } else {
            Db::startTrans();
            try {
                $wxService = new WeixinService();
                foreach ($template_no_list as $k => $v) {
                    if (!$wxService->delete_private_template($sid, $v)) {
                        Db::rollback();
                        return ['status' => 0, 'msg' => '删除模版ID为:' . $v . '时出错'];
                    }
                }
                db('wx_template')->where('sid', $sid)->delete();
                db('msg_setting')->where('sid', $sid)->delete();
                Db::commit();
                return ['status' => 1, 'msg' => '删除成功'];
            } catch (\Exception $e) {
                Db::rollback();
                return ['status' => 0, 'msg' => '删除失败'];
            }
        }
    }

    //一键配置
    public function AutoSetting(Request $request)
    {
        $sid = $request->param('sid');
        //获取配置内容
        $msg_list = db('msg_setting')->where(['sid' => $sid])->field('wx_template_type')->select();
        if (!empty($msg_list)) {
            foreach ($msg_list as $v) {
                $wx_template_type[] = $v['wx_template_type'];
            }
        }

        //获取初始化数据
        $init_data = db('wx_template_init')->where('status', 1)->whereIn('template_type', $wx_template_type)->select();
        foreach ($init_data as $k => $v) {
            //更新msg_setting
            if ($v['if_setting_receive'] == 1) {
                db('msg_setting')->where(['sid' => $sid, 'bussiness_no' => $v['id']])->update(['if_setting_receive' => 1]);
            }
            // 获得短ID
            $template_short_no = $init_data[$k]['template_short_no'];
            unset($init_data[$k]['template_short_no']);
            unset($init_data[$k]['id']);
            unset($init_data[$k]['if_setting_receive']);

            // 组合查询条件,当前的模板类型ID,和店铺ID组合确定唯一记录
            $where['sid'] = $sid;
            $where['template_type'] = $v['template_type'];

            //查看wx_template表中是否获取过模版Id
            $t_id = db('wx_template')->where($where)->find();
            if (empty($t_id)) {
                // 没有配置,用短ID去换长ID
                $wexin = new WeixinService();
                $temp_data = $wexin->get_template_id($sid, $template_short_no);
                if (!$temp_data) {
                    return ['status' => 0, 'msg' => '配置失败,请在微信公众平台后台模版消息处清空模版!'];
                }
                // 赋值长ID
                $init_data[$k]['template_no'] = $temp_data['template_id']; //模版Id
                // 没有记录就写入
                $init_data[$k]['sid'] = $sid;

                db('wx_template')->insert($init_data[$k]);
            } else {
                db('wx_template')->where($where)->update($init_data[$k]);
            }
        }
        return ['status' => 1];
    }


    /**
     * 一键配置模版消息
     * @param $sid
     * @return array
     */
    public function setAllMsg($sid)
    {
        //获取已配置过的模版
        $wx_template_type = db('msg_setting')->where('sid', $sid)->column('wx_template_type');

        //获取初始化数据
        $init_where = ['status' => 1];
        if ($wx_template_type) {
            $init_where['template_type'] = ['not in', $wx_template_type];
        }
        $init_data = db('wx_template_init')->where($init_where)->select();
        if (!$init_data) {
            return ['status' => 0, 'msg' => '配置失败，初始化数据为空'];
        }

        $wxService = new WeixinService();

        //判断模版消息是否超过25条(微信限制)，由于存在一条默认数据，总计26
        $template_list = $wxService->get_private_templates($sid);
        if (count($template_list) + count($init_data) > 26) {
            return ['status' => 0, 'msg' => '微信模版数量超过(25条)限制，请先点击"一键清除"按钮后，再进行配置'];
        }

        Db::startTrans();
        try {
            $msg_setting_data = [];
            $wx_template_data = [];
            foreach ($init_data as $k => $v) {
                // 添加微信模版消息
                $template = $wxService->get_template_id($sid, $v['template_short_no']);

                $wx_template_data[$k] = [
                    'sid' => $sid,
                    'template_no' => $template->template_id,
                    'template_type' => $v['template_type'],
                    'template_msg' => $v['template_msg'],
                    'template_msg_link' => $v['template_msg_link'],
                    'template_msg_content' => $v['template_msg_content'],
                    'template_list' => $v['template_list'],
                    'template_config' => $v['template_config'],
                    'status' => 1
                ];

                $msg_setting_data[$k] = [
                    'sid' => $sid,
                    'bussiness_no' => $v['template_type'] - 300,
                    'wx_template_type' => $v['template_type'],
                    'wx_status' => 1,
                    'if_setting_receive' => $v['if_setting_receive']
                ];
            }

            db('wx_template')->insertAll($wx_template_data);
            db('msg_setting')->insertAll($msg_setting_data);
            Db::commit();
            return ['status' => 1, 'msg' => '配置成功'];
        } catch (\Exception $e) {
            Db::rollback();
            // 若提示invalid template_id，极有可能是微信端已经将此模版删除了
            return ['status' => 0, 'msg' => '配置失败:'.$e->getMessage()];
        }
    }

    //消息模板详情
    public function GetMsgDetail(Request $request)
    {
        $msg_bussiness_no = \think\Config::get('msg_bussiness_no');
        $wx_template_msg = \think\Config::get('wx_template_msg');
        $wx_keywords_type = \think\Config::get('wx_keywords_type');
        $wx_template_msg_new = [];
        foreach ($wx_template_msg as $k => $v) {
            $wx_template_msg_new[] = ['key' => $k, 'value' => $v];
        }

        $wx_keywords_type_new = [];
        foreach ($wx_keywords_type as $k => $v) {
            $wx_keywords_type_new[] = ['key' => $k, 'value' => $v];
        }

        $template_id = $request->param('template_id');
        $sid = $request->param('sid');
        $info = db('wx_template')->where(array('sid' => $sid, 'template_id' => $template_id))->find();
        if (empty($info)) {
            return ['status' => 0];
        }
        $info['bussiness_name'] = $msg_bussiness_no[($info['template_type'] - 300)];
        $info['template_config_decode'] = array_values(json_decode($info['template_config'], 1));
        return [
            'status' => 1,
            'data' => [
                'content' => [
                    'info' => $info,
                    'msg_bussiness_no' => $msg_bussiness_no,
                    'wx_template_msg' => $wx_template_msg_new,
                    'wx_keywords_type' => $wx_keywords_type_new
                ]
            ]
        ];
    }

    //编辑
    public function MsgSetting(Request $request)
    {

        $postParam = $request->post();
        $config = [];
        foreach ($postParam['config'] as $k => $v) {
            $config[$k] = [
                'name' => urlencode($v['name']),
                'value' => urlencode($v['value']),
                'custom_value' => urlencode($v['custom_value']),
                'color' => urlencode($v['color']),
            ];

        }
        $template_msg_link = $request->has('template_msg_link') ? $postParam['template_msg_link'] : null;
        $data = [
            'sid' => $request->param('sid'),
            'template_no' => $postParam['template_no'],
            'template_type' => $postParam['template_type'],
            'template_msg' => $postParam['template_msg'],
            'template_msg_link' => $template_msg_link,
            'template_msg_content' => $postParam['template_msg_content'],
            'template_config' => urldecode(json_encode($config)),
            'status' => 1,
        ];
        $where = ['template_id' => $postParam['template_id']];
        $flag = db('wx_template')->where($where)->update($data);

        if ($flag !== false) {
            return ['status' => 1];
        } else {
            return ['status' => 0];
        }

    }

    //改变状态
    public function MsgStatusSetting(Request $request)
    {
        $where = [
            'sid' => $request->param('sid'),
            'setting_id' => $request->param('setting_id')
        ];
        $res = db('msg_setting')->where($where)->update(['wx_status' => $request->param('wx_status')]);
        if ($res !== false) {
            return ['status' => 1];
        } else {
            return ['status' => 0];
        }

    }

    /**
     * 设置消息接收人
     * @param $sid
     * @param $setting_id
     * @param $uid
     * @return array
     * @throws \think\Exception
     */
    public function MsgRecieveSetting($sid, $setting_id, $uid)
    {
        $where = [
            'sid' => $sid,
            'setting_id' => $setting_id
        ];
        $res = db('msg_setting')->where($where)->update(['receive_uids' => serialize($uid)]);
        if ($res !== false) {
            return ['status' => 1];
        } else {
            return ['status' => 0];
        }
    }


    public function delTplMsg($sid, $template_no)
    {
        $wxService = new WeixinService();
        $r = $wxService->delete_private_template($sid, $template_no);
        dump($r);
        die();
    }

    /**
     * 获取下一个模版操作编号
     * @return int
     */
    public static function getNextTemplateType()
    {
        $msg_bussiness_no = config('msg_bussiness_no');
        $max_key = max(array_keys($msg_bussiness_no));
        $next_template_type = (300 + $max_key) + 1;
        return $next_template_type;
    }


    /**
     * 设置template_list参数
     * @param $template_msg_content
     * @param bool $is_str
     * @return string
     */
    public static function setTemplateList($template_msg_content, $is_str = true)
    {
        preg_match_all('/\{\{(.*?)\}\}/', $template_msg_content, $matches);
        if ($is_str) {
            $template_list = implode('|', $matches[1]);
            return $template_list;
        } else {
            return $matches;
        }
    }

    /**
     * 设置template_config参数
     * @param $template_msg_content
     * @param string $type
     * @return array|string
     */
    public static function setTemplateConfig($template_msg_content, $type = 'json')
    {
        $template_list = self::setTemplateList($template_msg_content, false);
        $temp = $template_list[1];

        $data = [];
        foreach ($temp as $k => $v) {
            $data[$k]['name'] = $v;
            $data[$k]['value'] = 0;
            $data[$k]['custom_value'] = '';
            $data[$k]['color'] = '#333333';
        }
        if ($type == 'json') {
            return json_encode($data);
        } elseif ($type == 'array') {
            return $data;
        }
    }

    public static function getMsgBussinessNoFromConfig()
    {
        $bussiness_no = [];
        foreach (config('msg_bussiness_no') as $k => $v) {
            $bussiness_no[] = ['key' => $k, 'value' => $v];
        }
        return $bussiness_no;
    }

    public static function getWxKeywordsTypeFromConfig()
    {
        $wx_template_msg_new = [];
        foreach (config('wx_keywords_type') as $k => $v) {
            $wx_template_msg_new[] = ['key' => $k, 'value' => $v];
        }
        return $wx_template_msg_new;
    }


    public static function getWxTemplateMsgFromConfig()
    {
        $wx_template_msg_new = [];
        foreach (config('wx_template_msg') as $k => $v) {
            $wx_template_msg_new[] = ['key' => $k, 'value' => $v];
        }
        return $wx_template_msg_new;
    }


    /**
     * 重置初始化数据中template_config字段
     * @return array
     */
    public function resetTemplateConfig()
    {
        $init_data = db('wx_template_init')->where('status', 1)->select();
        foreach($init_data as $k => $v){
            $temp = json_decode($v['template_config'], 1);
            $template_type = $v['template_type'];
            // 下面的value值对应的配置文件(config.php)中wx_keywords_type的值
            switch($template_type){
                case 315:
                    $temp['keyword2.DATA']['value'] = '26';
                    break;
                case 321:
                    break;
                case 322:
                    break;
                case 325:
                    break;
                case 326:
                    break;
                case 327:
                    break;
                case 328:
                    $temp[0]['value'] = '0';
                    $temp[1]['value'] = '50';
                    $temp[2]['value'] = '51';
                    $temp[3]['value'] = '52';
                    $temp[4]['value'] = '53';
                    $temp[5]['value'] = '0';
                    break;
                case 329:
                    break;
                case 330:
                    $temp[0]['value'] = '0';
                    $temp[1]['value'] = '37';
                    $temp[2]['value'] = '61';
                    $temp[3]['value'] = '62';
                    $temp[4]['value'] = '0';
                    break;
                case 331:
                    $temp['first.DATA']['value'] = '0';
                    $temp['keyword1.DATA']['value'] = '37';
                    $temp['keyword2.DATA']['value'] = '63';
                    $temp['keyword3.DATA']['value'] = '64';
                    $temp['remark.DATA']['value'] = '0';
                    break;
                case 332:
                    $temp['keyword1.DATA']['value'] = '37';
                    $temp['keyword2.DATA']['value'] = '38';
                    break;
                case 333:
                    $temp['keyword1.DATA']['value'] = '37';
                    $temp['keyword2.DATA']['value'] = '38';
                    break;
                case 334:
                    $temp['keyword1.DATA']['value'] = '37';
                    $temp['keyword2.DATA']['value'] = '63';
                    $temp['keyword3.DATA']['value'] = '65';
                    $temp['keyword4.DATA']['value'] = '64';
                    $temp['keyword5.DATA']['value'] = '66';
                    break;
                case 335:
                    $temp['keyword1.DATA']['value'] = '63';
                    $temp['keyword2.DATA']['value'] = '67';
                    $temp['keyword3.DATA']['value'] = '37';
                    $temp['keyword4.DATA']['value'] = '39';
                    break;
            }

            $t = [];
            foreach($temp as $key=> $val){
                $t[] = $val;
            }

            $r = db('wx_template_init')->where('template_type', $template_type)->setField('template_config', json_encode($t));
            if($r === false){
                return ['status' => 0, 'msg' => '重置失败'];
            }
        }
        return ['status' => 1, 'msg' => '重置成功'];
    }

    /**
     * 重置初始化数据的状态(软删除配置文件中未配置的模版消息)
     * @return int
     */
    public function resetInitDataStatus()
    {
        $bussiness_no_list = config('msg_bussiness_no');
        $template_type_list = [];
        foreach($bussiness_no_list as $k => $v){
            $template_type_list[] = 300 + $k;
        }
        return db('wx_template_init')->where(['template_type' => ['not in', $template_type_list]])->setField('status', -1);
    }


    /**
     * 删除微信公众平台与本平台模版消息的差集(清除微信公众平台多余的模版消息)
     * @return array
     */
    public function deleteWxRedundantTplMsg()
    {
        $store_list = db('store')->where('status', 1)->column('store_id');
        if($store_list){
            $wxService = new WeixinService();
            foreach($store_list as $k => $v){
                if(!$this->isTemplateStore($v)){
                    // 获取微信公众平台每个店铺的模版消息列表
                    $tpls = $wxService->get_private_templates($v);

                    $tpl_no = [];
                    if($tpls){
                        foreach($tpls as $key => $val){
                            if($val['primary_industry']){
                                $tpl_no[] = $val['template_id'];
                            }
                        }
                    }

                    // 获取本地每个店铺的模版消息列表
                    $tpl_no_local = db('wx_template')->where('sid', $v)->column('template_no');

                    // 取出微信平台与本地模版消息的差集
                    $tpl_no_diff = array_diff($tpl_no, $tpl_no_local);

                    if($tpl_no_diff){
                        foreach($tpl_no_diff as $ky => $vy){
                            // 删除微信平台模版消息
                            if(!$wxService->delete_private_template($v, $vy)){
                                $err_msg = '店铺ID:'. $v . ', 删除模版ID: '. $vy . '时出错';
                                return ['status' => 0, 'msg' => $err_msg];
                            }
                        }
                    }
                }
            }
        }
        return ['status' => 1, 'msg' => '删除成功'];
    }
}